package com.sx.pipeline.ui.needs.operator

import android.app.Application
import android.text.TextUtils
import androidx.databinding.ObservableField
import com.alibaba.android.arouter.launcher.ARouter
import com.amap.api.services.core.PoiItem
import com.amap.api.services.geocoder.RegeocodeAddress
import com.blankj.utilcode.util.ToastUtils
import com.sx.mvvmlibs.base.BaseViewModel
import com.sx.mvvmlibs.bus.RxBus
import com.sx.mvvmlibs.event.SingleLiveEvent
import com.sx.mvvmlibs.http.CommonObserver
import com.sx.mvvmlibs.utils.Logs
import com.sx.mvvmlibs.utils.RxThreadHelper
import com.sx.pipeline.R
import com.sx.pipeline.app.config.OperatorNeedsType
import com.sx.pipeline.app.config.ReleaseNeedsType
import com.sx.pipeline.app.event.BusEvent
import com.sx.pipeline.app.event.EventTypes
import com.sx.pipeline.app.model.CYBaseViewModel
import com.sx.pipeline.arouth.RouteManager
import com.sx.pipeline.arouth.RoutePath
import com.sx.pipeline.repos.http.req.OmsNeedEquipment
import com.sx.pipeline.repos.http.req.OmsNeedUnit
import com.sx.pipeline.repos.http.req.ReleaseNeedsAddDTO
import com.sx.pipeline.repos.http.res.*
import com.sx.pipeline.ui.task.entity.ReleaseTaskListVO
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers

/**
 * @Author: YY
 * @Date: 2022/4/13
 * @Description: TODO
 */
class NeedsVM(app: Application) : CYBaseViewModel(app) {
    // 省ID
    val provinceIDField: ObservableField<Int> = ObservableField()

    // 市ID
    val cityIDField: ObservableField<Int> = ObservableField()

    // 区ID
    val areaIDField: ObservableField<Int> = ObservableField()

    //推送level
    val levelIDField: ObservableField<Int> = ObservableField()


    // 地址详情
    val addressField: ObservableField<String> = ObservableField()

    // 经度
    val longitudeField: ObservableField<String> = ObservableField()

    // 纬度
    val latitudeField: ObservableField<String> = ObservableField()

    /**
     * 获取我的需求类型标题
     */
    fun getNeedsTabsList(): List<String> {
        val tabs = mutableListOf<String>()
        tabs.add(getApplication<Application>().getString(R.string.txt_published))
        tabs.add(getApplication<Application>().getString(R.string.txt_cancelled))
        return tabs
    }

    /**
     * 获取运营单位需求类型id
     */
    fun getOperatorNeedsTabsId(): List<Int> {
        val tabs = mutableListOf<Int>()
        tabs.add(OperatorNeedsType.PUBLISHED.code)
        tabs.add(OperatorNeedsType.CANCELLED.code)
        return tabs
    }

    /**
     * 获取查找方式
     */
    fun getFindMethod(): List<String> {
        val pushRangeList: MutableList<String> = ArrayList()
        pushRangeList.add("系统内部查找")
        pushRangeList.add("发布需求信息")
        return pushRangeList
    }

    /**
     * 获取信息推送范围
     */
    fun getPushRange(): List<String> {
        //初始化推送范围
        val pushRangeList: MutableList<String> = ArrayList()
        pushRangeList.add("省")
        pushRangeList.add("市")
        pushRangeList.add("县")
        return pushRangeList
    }

    //地图页面拿到的位置数据
    val locationEvent: SingleLiveEvent<PoiItem> = SingleLiveEvent()
    override fun registerRxBus() {
        addSubscribe(
            RxBus.getDefault().toObservable(BusEvent::class.java)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    when (it.type) {
                        EventTypes.SELECT_SITE.code -> {
                            val poiItem: PoiItem = it.data as PoiItem
                            locationEvent.postValue(poiItem)
                            Logs.d("选择的地点：${poiItem.provinceName} === ${poiItem.cityName} === ${poiItem.adName}===${poiItem.title}===${poiItem.snippet} ")
                            Logs.d("选择的地点：${poiItem.latLonPoint.latitude} === ${poiItem.latLonPoint.longitude}")
                        }
                    }
                }
        )
    }


    /**
     * 获取需求配置数据
     */
    val taskListEvent: SingleLiveEvent<TaskConfigVo> = SingleLiveEvent()

    //需求标题
    val needTitleData: MutableList<String> = ArrayList()

    //需求类型
    val needTypeData: MutableList<String> = ArrayList()

    //计量单位
    val needUnitData: MutableList<String> = ArrayList()

    //结算方式
    val settleMethodData: MutableList<String> = ArrayList()
    fun getNeed() {
        addSubscribe(
            mModel.getNeed()
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<TaskConfigVo, BaseViewModel<*>>
                    (this, true) {

                    override fun onResult(result: TaskConfigVo) {
                        taskListEvent.postValue(result)
                        for (data in result.NEED_TITLE) {
                            needTitleData?.add(data.name)
                        }
                        for (data in result.TYPE_OF_REQUIREMENT) {
                            needTypeData?.add(data.name)
                        }
                        for (data in result.UNIT_OF_MEASUREMENT) {
                            needUnitData?.add(data.name)
                        }
                        for (data in result.SETTLEMENT_METHOD) {
                            settleMethodData?.add(data.name)
                        }
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort("$msg")

                    }
                })
        )
    }


    /**
     * 发布需求
     */
    fun addNeedOrder(
        type: Int, //需求类型 0设备查找  1.需求合作
        title: String, //标题
        description: String, //描述
        needType: String, //需求类型
        deviceName: String, //设备名称
        equipmentNo: String, //设备编号
        numberPlate: String, //车牌号
        equipmentImage: String,
        findBy: Int, //查找方式0:系统内部查找1:发布需求信息
        address: String, //地址
        addressDetail: String, //详细地址
        contact: String,
        contactPhone: String,
        quantity: String, //工作量
        unit: String, //计量单位
        startDate: String, //开始时间
        endDate: String, //结束时间
        pushRange: Int, //推送范围 推送范围0:省1:市2:区
        siteImage: String, //现场照片
        constructionImage: String,//施工图纸
    ) {

        if (TextUtils.isEmpty(title)) {
            ToastUtils.showShort("请选择标题")
            return
        }
//        if (TextUtils.isEmpty(description)) {
//            ToastUtils.showShort("请输入需求描述")
//            return
//        }
        if (TextUtils.isEmpty(needType)) {
            ToastUtils.showShort("请选择需求类型")
            return
        }
        if (TextUtils.isEmpty(addressDetail)) {
            ToastUtils.showShort("请输入详细地址")
            return
        }
        if (TextUtils.isEmpty(deviceName) && type == 0) {
            ToastUtils.showShort("请填写设备名称")
            return
        }
        if (TextUtils.isEmpty(equipmentNo) && type == 0) {
            ToastUtils.showShort("请填写产品编号")
            return
        }
        if (TextUtils.isEmpty(numberPlate) && type == 0) {
            ToastUtils.showShort("请填写车牌号码")
            return
        }
        if (TextUtils.isEmpty(quantity) && type == 1) {
            ToastUtils.showShort("请输入工作量")
            return
        }
        if (TextUtils.isEmpty(unit) && type == 1) {
            ToastUtils.showShort("请选择计量单位")
            return
        }


        if (TextUtils.isEmpty(addressDetail)) {
            ToastUtils.showShort("请选择施工地点")
            return
        }
        if (TextUtils.isEmpty(startDate) && type == 1) {
            ToastUtils.showShort("请选择开始时间")
            return
        }
        if (TextUtils.isEmpty(endDate) && type == 1) {
            ToastUtils.showShort("请选择结束时间")
            return
        }
        if (TextUtils.isEmpty(contact)) {
            ToastUtils.showShort("请选择联系人")
            return
        }
        if (TextUtils.isEmpty(contactPhone)) {
            ToastUtils.showShort("请填写联系电话")
            return
        }

        val dtoEnuipment =
            OmsNeedEquipment(deviceName, equipmentNo, numberPlate, findBy, equipmentImage)
        val dtoUnit =
            OmsNeedUnit(quantity, unit, startDate, endDate, pushRange, siteImage, constructionImage)
         val dto = ReleaseNeedsAddDTO(
                0,
                type,
                title,
                "",
                description,
                needType,
                provinceIDField.get()!!,
                cityIDField.get()!!,
                areaIDField.get()!!,
                longitudeField.get()!!,
                latitudeField.get()!!,
                address,
                addressDetail,
                dtoEnuipment,
                dtoUnit,
                null,
                contact,
                contactPhone
            )
            addSubscribe(
                mModel.addNeedOrder(dto)
                    .compose(RxThreadHelper.rxSchedulerHelper())
                    .subscribeWith(object : CommonObserver<Int, BaseViewModel<*>>
                        (this, true) {

                        override fun onResult(result: Int) {
                            if (findBy == 0 && type == 0) {
                                //系统内部查找 跳转设备详情
                                RouteManager.Mine.intentToDeviceDetail(result, true, true)
                            } else {
                                ToastUtils.showShort("需求发布完成")
                                ARouter.getInstance().build(RoutePath.Mine.RELEASE_RESULT)
                                    .navigation()
                                finish()
                            }

                        }

                        override fun onFailed(code: Int, msg: String?) {
                            super.onFailed(code, msg)
                            ToastUtils.showShort("$msg")
                            dismissLoadingDialog()
                        }
                    })
            )

    }


    /**
     * 获取我的需求列表
     */
    var mPage = 1
    val releaseSupplyListEvent: SingleLiveEvent<Ipage<ReleaseNeedsVO>> = SingleLiveEvent()
    fun operationPushNeedPage(status: Int, page: Int = 1) {
        addSubscribe(
            mModel.operationPushNeedPage(status, page)
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<Ipage<ReleaseNeedsVO>, BaseViewModel<*>>
                    (this, true) {
                    override fun onResult(result: Ipage<ReleaseNeedsVO>) {
                        releaseSupplyListEvent.postValue(result)
                        mUI.initRefreshEvent().postValue(true)
                        if (page != 1) {
                            mUI.initLoadEvent().postValue(true)
                        }
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort(msg)
                        mUI.initRefreshEvent().postValue(false)
                        if (page != 1) {
                            mUI.initLoadEvent().postValue(true)
                        }
                    }
                })
        )
    }

    /**
     * 取消需求
     */
    val successNeedEvent: SingleLiveEvent<Boolean> = SingleLiveEvent()
    fun cancelNeedOrder(id: Int) {
        addSubscribe(
            mModel.cancelNeedOrder(id)
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<Any, BaseViewModel<*>>
                    (this, true) {
                    override fun onResult(result: Any) {
                        ToastUtils.showShort("取消成功")
                        successNeedEvent.postValue(true)
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort(msg)
                    }
                })
        )
    }


    /**
     * 删除需求
     */
    fun deleteNeedOrder(id: Int) {
        addSubscribe(
            mModel.deleteNeedOrder(id)
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<Any, BaseViewModel<*>>
                    (this, true) {
                    override fun onResult(result: Any) {
                        ToastUtils.showShort("删除成功")
                        successNeedEvent.postValue(true)
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort(msg)
                    }
                })
        )
    }

    /**
     * 需求详情
     */
    val needOrderDetailEvent: SingleLiveEvent<ReleaseNeedsVO> = SingleLiveEvent()
    fun getNeedOrderDetail(id: Int) {
        addSubscribe(
            mModel.getNeedOrderDetail(id)
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<ReleaseNeedsVO, BaseViewModel<*>>
                    (this, true) {
                    override fun onResult(result: ReleaseNeedsVO) {
                        needOrderDetailEvent.postValue(result)
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort(msg)
                    }
                })
        )
    }
}